package roborally.program.commands;

import java.util.Iterator;

import roborally.model.Element;
import roborally.model.Item;
import roborally.model.Robot;

/**
 * A class for dealing with pick-up-and-use-commands: (pick-up-and-use).     
 * 
 * @version	1.0
 * @author  Pieter Robberechts	(1e Bach Informatica)
 * @author	Jeroen Sanders		(1e Bach Informatica)
 *
 */
public class PickUpAndUse extends BasicCommand{

	/**
	 * Initialize this new pick-up-and-use-command with a line number.
	 * 
	 */
	public PickUpAndUse(int lineNb) {
		super(lineNb);
	}

	/**
	 * Return a textual representation of this pick-up-and-use-command,
	 * formatted in accordance with its position in the program.
	 * 
	 * @return	The result is a pretty formatted string of this pick-up-command,
	 * 			taking in account his relative position in the program.
	 * 			| result == getIndentation(indentationLevel) + "(pick-up-and-use)"
	 */
	@Override
	public String prettyFormat(int indentationLevel) {
		return getIndentation(indentationLevel) + "(pick-up-and-use)";
	}

	/**
	 * Execute the pickUp and use method on a given robot.
	 * 
	 * @effect	The given robot picks-up a random item (if present) on his position
	 * 			and uses it immediately. 
	 * 			| ...
	 */
	@Override
	public void execute(Robot robot) throws IllegalArgumentException {
		super.execute(robot);
		Iterator<Element> elementsOnPositionRobot = robot.getBoard().getElements(robot.getPosition()).iterator();
		Item found = null;
		while(elementsOnPositionRobot.hasNext() && found == null) {
			Element next = elementsOnPositionRobot.next();
			if(next instanceof Item)
				found = (Item) next;
		}
		robot.pickUp(found);
		robot.use(found);		
	}

}
